<template>
	<view>
		<view class="x-page-border-top"></view>
		<scroll-view scroll-y="true" :style="{height: (device.windowHeight-device.footerHeight)+'px;'}">
			<x-address :address="address"></x-address>

			<template v-if="orderInfo && orderInfo.orderDetailEntityList">
				<x-product-and-delivery :data="orderInfo" @deliver="emitDeliver"
					@msg="emitMsg"></x-product-and-delivery>

				<view class="input">
					<view>商品金额</view>
					<!-- <view style="color:red;">￥{{meetAmount}}</view> -->
					<price :value="orderInfo.meetAmount" style="color:red;" />
				</view>
				<!-- <view class="input">
					<view>代金券</view>
					<view class="picker">
						<view class="placeholder" v-if="couponList.length == 0" @click="showCoupon = true">暂无可用代金券
						</view>
						<template v-else>
							<view class="placeholder" v-if="coupon.id" @click="showCoupon = true"><text
									class="text_red">-￥{{coupon.couponMoney}}</text></view>
							<view class="placeholder" v-else @click="showCoupon = true">{{couponList.length}}张可用代金券
							</view>
						</template>

						<u-icon name="arrow-right" color="xIconColor()" size="10"></u-icon>
					</view>
				</view> -->
				<view class="input">
					<view>折扣抵扣金额</view>
					<view>{{0}}</view>
				</view>
				<view class="input">
					<view>支付方式</view>
					<view>
						<picker @change="selectPayType" :value="payType" :range="payTypeList" range-key="label">
							<view class="picker">
								{{payTypeList[payType].label}}
							</view>
						</picker>
					</view>
				</view>

				<view class="order_info">合计<text class="text_red">￥{{orderInfo.paidAmount}}</text></view>

				<view class="border"></view>
				<view class="input">
					<view>发票</view>
					<view class="picker">
						<view v-if="invoice.id" @click="selectInvoice">
							{{invoice.invoiceTypeCode == 'GENERAL_VAT'?'普通发票':'专用发票'}}-{{invoice.invoiceTitleType == 1?'个人':'单位'}}
						</view>
						<view class="placeholder" v-else @click="selectInvoice">选择发票类型</view>
						<u-icon name="arrow-right" color="xIconColor()" size="10"></u-icon>
					</view>
				</view>
				<view class="border"></view>
			</template>
		</scroll-view>

		<!-- 底部按钮 -->
		<x-footer>
			<view style="display: flex;flex-direction: column;">
				<u-text size="20" prefixIcon="￥" iconStyle="font-size: 12px;color:red" color="red"
					:text="orderInfo.paidAmount"></u-text>
				<text style="font-size: 12px;color: #909399;">共优惠￥{{preferentialAmount}}</text>
			</view>
			<button class="btn_sub x-btn" @click="onSub">支付订单</button>
		</x-footer>

		<u-popup :show="showCoupon" @open="open">
			<view class="alert">
				<view class="user_name">代金券</view>
				<u-tabs :list="couponStatus" @click="changeStatus" lineWidth="26" :lineColor="xThemeColor()"></u-tabs>
				<view class="coupon_list" v-if="currentStatus == 0">

<!-- v-model="couponSelIndex" -->
					<u-radio-group :value="couponSelIndex"  placement="column" @change="slelectCoupon"
						v-if="couponList.length>0">
						<view class="item" v-for="(i,index) in couponList" :key="i.id">
							<view class="item_left">
								<view>￥<text class="item_price">{{i.couponMoney}}</text></view>
								<view>满减券</view>
							</view>
							<view class="item_content">
								<view class="item_title">{{i.name}}</view>
								<view style="margin: 20rpx 0;">满{{i.fullMoney}}元可用</view>
								<view>有效期至{{i.endTime}}</view>
							</view>
							<!-- <checkbox :value="index" color="#e1251b" /> -->
							<u-radio :name="index" color="#e1251b"></u-radio>

						</view>
					</u-radio-group>


					<u-empty mode="coupon" v-else text="暂无可用代金券"></u-empty>
				</view>
				<view class="disable_coupon" v-else>
					<view v-if="disableCoupon.length>0">
						<view class="item" v-for="(i,index) in disableCoupon" :key="i.id">
							<view class="item_left">
								<view>￥<text class="item_price">{{i.couponMoney}}</text></view>
								<view>满减券</view>
							</view>
							<view class="item_content">
								<view class="item_title">{{i.name}}</view>
								<view style="margin: 20rpx 0;">满{{i.fullMoney}}元可用</view>
								<view>有效期至{{i.endTime}}</view>
							</view>
						</view>

					</view>
					<u-empty mode="coupon" v-else text="暂无不可用代金券"></u-empty>
				</view>
				<view class="ic_close" @click="showCoupon = false"><u-icon name="close-circle" size="28"></u-icon>
				</view>
				<button class="btn_enter x-btn" @click="showCoupon = false">确认</button>
			</view>
		</u-popup>


	</view>
</template>

<script>
	import {
		pay,
		getInfo
	} from '@/api/order.js';
	import {
		getAddress
	} from '@/api/address.js';
	import config from '@/config';
	import {
		getShop
	} from '@/api/shop.js'
	import {
		mapState
	} from 'vuex'
	import EventBusMacro from '@/plugins/EventBus/eventBusMacro.js'
	import XAddress from '@/pages/components/address/xAddress.vue'
	import XProductAndDelivery from '@/pages/components/productAndDelivery/xProductAndDelivery.vue'
	import {
		ThemeMixin
	} from '@/mixins/theme/xThemeMixin.js'
	
	export default {
		mixins: [ThemeMixin],
		computed: {
			...mapState(['device']),
		},
		components: {
			XAddress,
			XProductAndDelivery,
		},

		data() {
			return {
				showCoupon: false,
				orderInfo: null,
				payTypeList:[
					{label:'微信',value:1},
					{label:'挂账',value:2},
					{label:'钱包余额',value:3},
				],
				payType:0,
				couponStatus: [{
					name: '可用'
				}, {
					name: '不可用'
				}],
				currentStatus: 0,
				couponList: [],
				disableCoupon: [],
				invoice: {
					id: ''
				},
				imageUrl: config.imageUrl, //
				address: {},
				isCar: false,
				shopList: [],
				total: 0,
				isCar: 0,
				shopName: '',

				// 与金额、积分相关参数
				meetAmount: 0, // 应付金额 （仅商品价格*商品数量，不扣减优惠劵、打折相关）
				paidAmount: 0, //实际支付金额 = 【 （应付金额 -  优惠劵）* 打折 】
				coupon: {
					couponMoney: 0,
					id: ''
				},
				discountAmount: 0, //折扣扣件金额
				preferentialAmount: 0, //总优惠金额
				integration: 0, //所获取的积分

				couponSelIndex: -1, //所选优惠劵索引值
			};
		},

		mounted() {},
		beforeDestroy() {
			this.$events.off(EventBusMacro.EB_ADDRESS_CHANGE, this.onAddressChange)
			this.$events.off(EventBusMacro.EB_INVOICE_CHANGE, this.onInvoiceChange)
		},
		onLoad(options) {
			
			this.$events.on(EventBusMacro.EB_ADDRESS_CHANGE, this.onAddressChange)
			this.$events.on(EventBusMacro.EB_INVOICE_CHANGE, this.onInvoiceChange)

			this.address = uni.getStorageSync('address') || {};

			this.isCar = options.isCar;
			if (options.checkedList) {
				this.checkedList = JSON.parse(options.checkedList)
			}
			this.getInfo(options.id);
			
			console.log("this.orderInfo=", this.orderInfo)
			this.getCoupon();

			this.meetAmount = options.totalAmount
			this.paidAmount = this.meetAmount
			// this.getShops()
		},
		methods: {
			selectPayType(e){
				console.log(e)
				this.payType = e.detail.value;
			},
		
			getInfo(id){
				getInfo(id).then(res=>{
					this.orderInfo = res;
				})
			},
			
			emitDeliver(newPickingType) {
				console.log("emitDeliver orderInfo.pickingType=", this.orderInfo.pickingType, ", newPickingType=",
					newPickingType)
				this.orderInfo.pickingType = newPickingType
			},
			emitMsg(newRemarkMsg) {
				console.log("emitMsg orderInfo.remark=", this.orderInfo.remark, ", newRemarkMsg=", newRemarkMsg)
				this.orderInfo.remark = newRemarkMsg
			},
			onAddressChange(newAddress) {
				this.address = newAddress;
			},
			onInvoiceChange(newInvoice) {
				this.invoice = newInvoice
			},
			changeStatus(e) {
				this.currentStatus = e.index;
			},
			close() {

			},
			open() {

			},
			getUserPoints(e) {
				const num = e.toFixed(0);
				return Number(num)
			},
			getCoupon() {
				const coupon = this.orderInfo.coupons.filter(item => {
					return item.fullMoney <= this.orderInfo.orders[0].meetAmount;
				})
				const disableCoupon = this.orderInfo.coupons.filter(item => {
					return item.fullMoney > this.orderInfo.orders[0].meetAmount;
				})
				console.log("getCoupon coupon=", coupon)
				this.couponList = coupon;
				this.disableCoupon = disableCoupon;
			},
			getName(e) {
				const shop = this.shopList.find(item => item.id === e)
				console.log('shop.name', shop)
				return shop?.name
			},
			getShops() {
				getShop().then(res => {
					this.shopList = res
				})
			},
			slelectCoupon(e) {
				if (this.couponSelIndex == -1 || this.couponSelIndex != e) {
					this.couponSelIndex = e
					this.coupon = this.couponList[this.couponSelIndex] 
				} else {
					this.couponSelIndex = -1
					this.coupon = {
						couponMoney: 0,
						id: ''
					};
				}
				// let index = e
				// this.coupon = this.couponList[index] ? this.couponList[index] : {
				// 	couponMoney: 0,
				// 	id: ''
				// };
			},
			selectInvoice(e) {
				uni.navigateTo({
					url: '/pages/mine/invoice/chooseInvoice?isSelected=true'
				})
			},

			onSub() {
				const orderInfo = this.orderInfo;
				orderInfo.couponId = this.coupon.id;
				orderInfo.clientAddressId = this.address.id;
				orderInfo.invoiceId = this.invoice.id;
				orderInfo.settlement = Number(this.payType)+1;
				if (!orderInfo.clientAddressId&&orderInfo.pickingType == 1) {
					uni.showToast({
						title: '请选择收货地址',
						icon: 'none'
					});
					return false;
				}
				pay(orderInfo).then(res => {
						uni.reLaunch({
							url: '/pages/mine/order/index',
							complete:c=>{
								console.log('支付成功',c)
							}
						});
						return
						// this.delGoods();
						if (res.pay) {
							let result = res.pay;
							uni.requestPayment({
								timeStamp: result.timeStamp,
								nonceStr: result.nonceStr,
								package: result.package,
								signType: result.signType,
								paySign: result.paySign,
								success: resPay => {
									if (resPay.errMsg == 'requestPayment:ok') {
										//支付成功跳转到我的订单
										uni.switchTab({
											url: '/pages/mine/index'
										});
									} else {
										uni.showToast({
											icon: 'none',
											title: '支付失败',
											success: () => {
												uni.switchTab({
													url: '/pages/mine/index'
												});
											}
										});
									}
								},
								fail: f => {
									uni.switchTab({
										url: '/pages/mine/index'
									});
								},
								complete: c => {
									console.log('ccc', c)
								}
							});
						} else {
							uni.showToast({
								icon: 'none',
								title: '已取消支付',
								success: () => {
									uni.switchTab({
										url: '/pages/mine/index'
									});
								}
							});
						}
					})
					.catch(error => {
						// 业务异常代码代码code
						if (error.httpCode === 409 || error.httpCode === 4001) {
							// this.delGoods() //购物车里面的数据信息与后台的不一致，有可能是库存不足 或 价钱 前后台不一致
							this.$TOOLS.UNI.showToast(error.message)
						}
					});
			},
			delGoods() {
				// 有来源于 “订单未支付” 和 “购物车”，只有来源于 “购物车” 才需要清理购物车
				if (this.isCar) {
					const car = uni.getStorageSync('car');
					const newCar = new Array();
					for (var i = 0; i < car.length; i++) {
						var inHere = false;
						for (var j = 0; j < this.checkedList.length; j++) {
							if (car[i].id == this.checkedList[j].goodsId) {
								inHere = true;
							}
						}
						if (!inHere) {
							newCar.push(car[i]);
						}
					}
					uni.setStorageSync('car', newCar);
				} else {
					return false;
				}
			},
			// 查询收货地址
			getAddress() {
				getAddress()
					.then(res => {
						console.log('1111111111', res)
						for (var i = 0; i < res.length; i++) {
							if (res[i].defaultAddress == 1) {
								this.address = res[i];
							}
						}
					})
					.catch(error => {});
			}
		}
	};
</script>

<style lang="scss">
	@import "@/mixins/theme/xTheme.scss";

	.youhui {
		font-size: 26rpx;
		margin-top: 10rpx;
	}

	.first_gift_text {
		border: 1rpx solid #e1251b;
		color: #e1251b;
		font-size: 24rpx;
		padding: 2rpx 4rpx;
		display: inline-block;
		margin-top: 4rpx;
	}

	.alert {
		padding: 40rpx 20rpx;
		position: relative;

		.ic_close {
			position: absolute;
			top: 20rpx;
			right: 20rpx;
		}

		.user_name {
			padding: 0 20rpx;
		}

		.alert_text {
			color: #515151;
			font-size: 28rpx;
			margin: 40rpx auto;
			padding: 0 20rpx;
		}

		.btn_enter {
			width: 100%;
			height: 90rpx;
			// background-color: #6A65CF;
			margin: 50rpx auto 20rpx;
			border-radius: 6rpx;
			// color: #fff;
		}

		.coupon_list {
			height: 50vh;
			width: 100%;
			overflow-y: scroll;
			margin: 30rpx auto;

			.item {
				width: 690rpx;
				height: 200rpx;
				background-color: #fff;
				border-radius: 6rpx;
				box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.3);
				margin: 0 auto 20rpx;
				display: flex;
				align-items: center;
				overflow: hidden;
				justify-content: space-between;
				padding-right: 30rpx;

				.item_left {
					width: 200rpx;
					height: 300rpx;
					background-color: #e1251b;
					border-top-right-radius: 100%;
					border-bottom-right-radius: 100%;
					display: flex;
					align-items: center;
					justify-content: center;
					flex-direction: column;
					color: #fff;
					font-size: 30rpx;
				}

				.item_price {
					font-size: 50rpx;
					font-weight: bold;
				}

				.item_content {
					font-size: 26rpx;
					color: #d5d5d5;
					margin-left: 20rpx;
				}

				.item_title {
					font-size: 32rpx;
					color: #333;
				}
			}
		}

		.disable_coupon {
			height: 50vh;
			width: 100%;
			overflow-y: scroll;
			margin: 30rpx auto;

			.item {
				width: 690rpx;
				height: 200rpx;
				background-color: #fff;
				border-radius: 6rpx;
				box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.3);
				margin: 0 auto 20rpx;
				display: flex;
				align-items: center;
				overflow: hidden;
				justify-content: space-between;
				padding-right: 30rpx;

				.item_left {
					width: 200rpx;
					height: 300rpx;
					background-color: #c2c2c2;
					border-top-right-radius: 100%;
					border-bottom-right-radius: 100%;
					display: flex;
					align-items: center;
					justify-content: center;
					flex-direction: column;
					color: #fff;
					font-size: 30rpx;
				}

				.item_price {
					font-size: 50rpx;
					font-weight: bold;
				}

				.item_content {
					font-size: 26rpx;
					color: #d5d5d5;
					margin-left: 20rpx;
				}

				.item_title {
					font-size: 32rpx;
					color: #333;
				}
			}
		}
	}

	.gift {
		heigh: 180rpx;
	}

	.gift image {
		height: 180rpx;
	}

	.text_red {
		color: #e51c23;
		font-weight: bold;
		font-size: 32rpx;
	}

	.ic_right_picker {
		width: 36rpx;
		height: 36rpx;
		margin-left: 10rpx;
	}

	.border {
		width: 100%;
		height: 20rpx;
		background-color: #f0f0f0;
	}

	.input {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 20rpx;
		height: 90rpx;
		font-size: 28rpx;

		.picker {
			display: flex;
			align-items: center;

			&>image {
				width: 36rpx;
				height: 36rpx;
				font-size: 28rpx;
				margin-left: 10rpx;
			}

			.placeholder {
				font-size: 28rpx;
				color: #707070;
			}
		}

		&>input {
			width: 440rpx;
			font-size: 28rpx;
			text-align: right;
		}
	}

	.order_info {
		font-size: 28rpx;
		height: 90rpx;
		text-align: right;
		line-height: 90rpx;
		padding: 0 20rpx;
	}

	.footer {
		width: 100%;
		height: 90rpx;
		background-color: #fff;
		position: fixed;
		z-index: 1;
		display: flex;
		padding: 0 20rpx;
		align-items: center;
		justify-content: space-between;
		border-top: 2rpx solid rgba(0, 0, 0, 0.1);

		.btn_sub {
			width: 24%;
			display: flex;
			background-color: #e51c23;
			color: #fff;
			align-items: center;
			justify-content: center;
			border-radius: 100rpx;
			height: 64rpx;
		}
	}

	.btn_sub {
		width: 24%;
		display: flex;
		color: #fff;
		align-items: center;
		justify-content: center;
		border-radius: 100rpx;
		height: 64rpx;
	}

	.check_box {
		width: 40rpx;
		height: 40rpx;
		border-radius: 40rpx;
		border: 2rpx solid #909399;
		margin-right: 20rpx;
		display: flex;
	}

	.checked {
		background-color: #e51c23;
		border-color: #e51c23;
	}

	.check_box>image {
		width: 32rpx;
		height: 32rpx;
		margin: auto;
	}

	.default {
		display: flex;
		justify-content: center;
		color: white;
		background-color: red;
		border-radius: 5px;
		font-size: 12px;
		padding: 4rpx;
	}
</style>